<template>
	<view class="container">
		<form @submit="handleSubmit">
			<!-- 类型选择 -->
			<view class="form-group">
				<text class="form-label">类型</text>
				<view class="type-buttons">
					<button 
						type="button"
						class="type-btn"
						:class="{ active: formData.type === 'schedule' }"
						@click="setType('schedule')"
					>
						<uni-icons type="calendar" size="16" />
						<text>日程</text>
					</button>
					<button 
						type="button"
						class="type-btn"
						:class="{ active: formData.type === 'task' }"
						@click="setType('task')"
					>
						<uni-icons type="checkbox" size="16" />
						<text>任务</text>
					</button>
				</view>
				<text class="type-desc">
					{{ formData.type === 'schedule' ? '有明确时间安排的事项' : '无时间限制的待办事项' }}
				</text>
			</view>

			<!-- 标题输入 -->
			<view class="form-group">
				<text class="form-label">标题 *</text>
				<input 
					class="form-input"
					type="text"
					v-model="formData.title"
					:placeholder="formData.type === 'schedule' ? '请输入日程标题' : '请输入任务标题'"
					maxlength="50"
				/>
			</view>

			<!-- 时间设置 - 仅日程类型显示 -->
			<view class="form-group" v-if="formData.type === 'schedule'">
				<text class="form-label">时间设置</text>
				<view class="time-row">
					<view class="time-item">
						<text class="time-label">开始时间</text>
						<picker 
							mode="multiSelector"
							:value="startTimeIndex"
							:range="timeRange"
							@change="onStartTimeChange"
							class="time-picker"
						>
							<view class="picker-display">
								<text>{{ formatDisplayTime(formData.startTime) }}</text>
								<uni-icons type="arrowdown" size="16" color="#6B7280" />
							</view>
						</picker>
					</view>
					<view class="time-item">
						<text class="time-label">截止时间</text>
						<picker 
							mode="multiSelector"
							:value="endTimeIndex"
							:range="timeRange"
							@change="onEndTimeChange"
							class="time-picker"
						>
							<view class="picker-display">
								<text>{{ formatDisplayTime(formData.endTime) }}</text>
								<uni-icons type="arrowdown" size="16" color="#6B7280" />
							</view>
						</picker>
					</view>
				</view>
			</view>

			<!-- 重复设置 - 仅日程类型显示 -->
			<view class="form-group" v-if="formData.type === 'schedule'">
				<text class="form-label">重复周期</text>
				<picker 
					:value="repeatIndex"
					:range="repeatOptions"
					range-key="label"
					@change="onRepeatChange"
					class="form-picker"
				>
					<view class="picker-display">
						<text>{{ repeatOptions[repeatIndex].label }}</text>
						<uni-icons type="arrowdown" size="16" color="#6B7280" />
					</view>
				</picker>
			</view>

			<!-- 优先级设置 -->
			<view class="form-group">
				<text class="form-label">紧急程度</text>
				<view class="priority-buttons">
					<button 
						v-for="option in priorityOptions"
						:key="option.value"
						type="button"
						class="priority-btn"
						:class="[
							`priority-${option.value}`,
							{ active: formData.priority === option.value }
						]"
						@click="setPriority(option.value)"
					>
						{{ option.label }}
					</button>
				</view>
			</view>

			<!-- 标签设置 -->
			<view class="form-group">
				<text class="form-label">分类标签</text>
				<view class="tags-section">
					<view class="available-tags">
						<button 
							v-for="tag in availableTags"
							:key="tag"
							type="button"
							class="tag-btn"
							:class="{ active: formData.tags.includes(tag) }"
							@click="toggleTag(tag)"
						>
							{{ tag }}
						</button>
					</view>
					<view class="custom-tag-input">
						<input 
							class="tag-input"
							type="text"
							v-model="newTag"
							placeholder="添加自定义标签"
							@confirm="addCustomTag"
						/>
						<button 
							type="button"
							class="add-tag-btn"
							@click="addCustomTag"
							:disabled="!newTag.trim()"
						>
							添加
						</button>
					</view>
				</view>
			</view>

			<!-- 描述输入 -->
			<view class="form-group">
				<text class="form-label">详细描述</text>
				<textarea 
					class="form-textarea"
					v-model="formData.description"
					placeholder="请输入详细描述（可选）"
					maxlength="200"
					:show-count="true"
				></textarea>
			</view>

			<!-- 提醒设置 -->
			<view class="form-group">
				<text class="form-label">提醒设置</text>
				<view class="reminder-section">
					<view class="reminder-toggle">
						<switch 
							:checked="formData.reminder.enabled"
							@change="onReminderToggle"
							color="#3B82F6"
						/>
						<text class="reminder-label">启用提醒</text>
					</view>
					<view v-if="formData.reminder.enabled" class="reminder-options">
						<picker 
							:value="reminderIndex"
							:range="reminderOptions"
							range-key="label"
							@change="onReminderChange"
							class="reminder-picker"
						>
							<view class="picker-display">
								<text>{{ reminderOptions[reminderIndex].label }}</text>
								<uni-icons type="arrowdown" size="16" color="#6B7280" />
							</view>
						</picker>
					</view>
				</view>
			</view>

			<!-- 提交按钮 -->
			<view class="form-actions">
				<button 
					class="btn-primary submit-btn"
					form-type="submit"
					:disabled="!isFormValid"
				>
					{{ isEditMode ? (formData.type === 'schedule' ? '更新日程' : '更新任务') : (formData.type === 'schedule' ? '创建日程' : '创建任务') }}
				</button>
			</view>
		</form>
	</view>
</template>

<script>
import { mapGetters, mapActions } from 'vuex'

export default {
	name: 'CreatePage',
	
	data() {
		return {
			isEditMode: false,
			editingId: null,
			newTag: '',
			
			formData: {
				type: 'schedule', // 默认为日程类型
				title: '',
				startTime: '',
				endTime: '',
				repeat: 'none',
				priority: 'medium',
				tags: [],
				description: '',
				reminder: {
					enabled: false,
					beforeMinutes: 30
				}
			},
			
			// 时间选择器数据
			startTimeIndex: [0, 0, 0],
			endTimeIndex: [0, 0, 0],
			timeRange: [[], [], []], // [日期, 小时, 分钟]
			
			// 重复选项
			repeatIndex: 0,
			repeatOptions: [
				{ value: 'none', label: '不重复' },
				{ value: 'daily', label: '每日' },
				{ value: 'weekly', label: '每周' },
				{ value: 'monthly', label: '每月' },
				{ value: 'yearly', label: '每年' }
			],
			
			// 提醒选项
			reminderIndex: 1 // 对应30分钟前
		}
	},
	
	computed: {
		...mapGetters('settings', ['priorityOptions', 'reminderOptions']),
		
		// 可用标签
		availableTags() {
			return this.$store.state.settings.defaults.tags || []
		},
		
		// 表单验证
		isFormValid() {
			const hasTitle = this.formData.title.trim()
			
			// 任务类型只需要标题
			if (this.formData.type === 'task') {
				return hasTitle
			}
			
			// 日程类型需要标题和有效时间
			return hasTitle && 
				   this.formData.startTime && 
				   this.formData.endTime &&
				   new Date(this.formData.endTime) > new Date(this.formData.startTime)
		}
	},
	
	onLoad(options) {
		this.initTimeRange()
		
		if (options.mode === 'edit' && options.id) {
			this.isEditMode = true
			this.editingId = options.id
			this.loadScheduleData(options.id)
		} else {
			this.initDefaultData()
		}
	},
	
	methods: {
		...mapActions('schedule', ['addSchedule', 'updateSchedule']),
		...mapActions('settings', ['loadSettings']),
		
		// 初始化时间选择器范围
		initTimeRange() {
			const dates = []
			const hours = []
			const minutes = []
			
			// 生成未来30天的日期
			for (let i = 0; i < 30; i++) {
				const date = new Date()
				date.setDate(date.getDate() + i)
				const month = (date.getMonth() + 1).toString().padStart(2, '0')
				const day = date.getDate().toString().padStart(2, '0')
				dates.push(`${month}月${day}日`)
			}
			
			// 生成24小时
			for (let i = 0; i < 24; i++) {
				hours.push(i.toString().padStart(2, '0') + '时')
			}
			
			// 生成60分钟（每分钟）
			for (let i = 0; i < 60; i++) {
				minutes.push(i.toString().padStart(2, '0') + '分')
			}
			
			this.timeRange = [dates, hours, minutes]
		},
		
		// 初始化默认数据
		async initDefaultData() {
			await this.loadSettings()
			
			const now = new Date()
			const startTime = new Date(now.getTime() + 60 * 60 * 1000) // 1小时后
			const endTime = new Date(startTime.getTime() + 60 * 60 * 1000) // 再1小时后
			
			this.formData.startTime = startTime.toISOString()
			this.formData.endTime = endTime.toISOString()
			this.formData.priority = this.$store.state.settings.defaults.priority
			this.formData.reminder.beforeMinutes = this.$store.state.settings.notifications.scheduleReminderMinutes
			
			this.updateTimeIndexes()
		},
		
		// 加载要编辑的日程数据
		loadScheduleData(id) {
			const schedule = this.$store.state.schedule.schedules.find(s => s.id === id)
			if (schedule) {
				this.formData = { ...schedule }
				this.updateTimeIndexes()
				this.updatePickerIndexes()
			}
		},
		
		// 更新时间选择器索引
		updateTimeIndexes() {
			// 更新开始时间索引
			const startDate = new Date(this.formData.startTime)
			this.startTimeIndex = this.getTimeIndex(startDate)
			
			// 更新结束时间索引
			const endDate = new Date(this.formData.endTime)
			this.endTimeIndex = this.getTimeIndex(endDate)
		},
		
		// 更新其他选择器索引
		updatePickerIndexes() {
			// 重复周期
			this.repeatIndex = this.repeatOptions.findIndex(opt => opt.value === this.formData.repeat)
			if (this.repeatIndex === -1) this.repeatIndex = 0
			
			// 提醒时间
			this.reminderIndex = this.reminderOptions.findIndex(opt => opt.value === this.formData.reminder.beforeMinutes)
			if (this.reminderIndex === -1) this.reminderIndex = 1
		},
		
		// 获取时间在选择器中的索引
		getTimeIndex(date) {
			const now = new Date()
			const dayDiff = Math.floor((date - now) / (1000 * 60 * 60 * 24))
			const dateIndex = Math.max(0, Math.min(dayDiff, 29))
			const hourIndex = date.getHours()
			const minuteIndex = date.getMinutes()
			
			return [dateIndex, hourIndex, minuteIndex]
		},
		
		// 开始时间变化
		onStartTimeChange(e) {
			const indexes = e.detail.value
			this.startTimeIndex = indexes
			
			const now = new Date()
			const targetDate = new Date(now)
			targetDate.setDate(now.getDate() + indexes[0])
			targetDate.setHours(indexes[1])
			targetDate.setMinutes(indexes[2])
			targetDate.setSeconds(0)
			
			this.formData.startTime = targetDate.toISOString()
			
			// 确保结束时间晚于开始时间
			if (new Date(this.formData.endTime) <= targetDate) {
				const endTime = new Date(targetDate.getTime() + 60 * 60 * 1000)
				this.formData.endTime = endTime.toISOString()
				this.endTimeIndex = this.getTimeIndex(endTime)
			}
		},
		
		// 结束时间变化
		onEndTimeChange(e) {
			const indexes = e.detail.value
			this.endTimeIndex = indexes
			
			const now = new Date()
			const targetDate = new Date(now)
			targetDate.setDate(now.getDate() + indexes[0])
			targetDate.setHours(indexes[1])
			targetDate.setMinutes(indexes[2])
			targetDate.setSeconds(0)
			
			// 确保结束时间晚于开始时间
			if (targetDate > new Date(this.formData.startTime)) {
				this.formData.endTime = targetDate.toISOString()
			} else {
				uni.showToast({
					title: '结束时间不能早于开始时间',
					icon: 'none'
				})
			}
		},
		
		// 重复周期变化
		onRepeatChange(e) {
			this.repeatIndex = e.detail.value
			this.formData.repeat = this.repeatOptions[this.repeatIndex].value
		},
		
		// 提醒开关
		onReminderToggle(e) {
			this.formData.reminder.enabled = e.detail.value
		},
		
		// 提醒时间变化
		onReminderChange(e) {
			this.reminderIndex = e.detail.value
			this.formData.reminder.beforeMinutes = this.reminderOptions[this.reminderIndex].value
		},
		
		// 设置优先级
		setPriority(priority) {
			this.formData.priority = priority
		},
		
		// 设置类型
		setType(type) {
			this.formData.type = type
			
			// 切换到任务类型时，清空时间相关字段
			if (type === 'task') {
				this.formData.startTime = ''
				this.formData.endTime = ''
				this.formData.repeat = 'none'
				this.repeatIndex = 0
			} else if (type === 'schedule' && !this.formData.startTime) {
				// 切换到日程类型时，如果没有时间，设置默认时间
				this.initDefaultData()
			}
		},
		
		// 切换标签
		toggleTag(tag) {
			const index = this.formData.tags.indexOf(tag)
			if (index > -1) {
				this.formData.tags.splice(index, 1)
			} else {
				this.formData.tags.push(tag)
			}
		},
		
		// 添加自定义标签
		addCustomTag() {
			const tag = this.newTag.trim()
			if (tag && !this.formData.tags.includes(tag)) {
				this.formData.tags.push(tag)
				this.$store.commit('settings/ADD_TAG', tag)
				this.newTag = ''
			}
		},
		
		// 格式化显示时间
		formatDisplayTime(timeString) {
			if (!timeString) return '请选择时间'
			
			const date = new Date(timeString)
			const month = (date.getMonth() + 1).toString().padStart(2, '0')
			const day = date.getDate().toString().padStart(2, '0')
			const hours = date.getHours().toString().padStart(2, '0')
			const minutes = date.getMinutes().toString().padStart(2, '0')
			
			return `${month}/${day} ${hours}:${minutes}`
		},
		
		// 提交表单
		async handleSubmit() {
			if (!this.isFormValid) {
				uni.showToast({
					title: '请填写完整信息',
					icon: 'none'
				})
				return
			}
			
			try {
				const scheduleData = {
					...this.formData,
					completed: false
				}
				
				// 为任务类型设置默认时间（用于排序和统计）
				if (this.formData.type === 'task') {
					const now = new Date()
					scheduleData.startTime = now.toISOString()
					// 任务设置一个很远的截止时间，表示无时间限制
					const farFuture = new Date(now.getTime() + 365 * 24 * 60 * 60 * 1000) // 一年后
					scheduleData.endTime = farFuture.toISOString()
				}
				
				if (this.isEditMode) {
					await this.updateSchedule({
						id: this.editingId,
						updates: scheduleData
					})
					uni.showToast({
						title: '更新成功',
						icon: 'success'
					})
				} else {
					await this.addSchedule(scheduleData)
					uni.showToast({
						title: '创建成功',
						icon: 'success'
					})
				}
				
				// 返回上一页
				setTimeout(() => {
					uni.navigateBack()
				}, 1500)
			} catch (error) {
				uni.showToast({
					title: '操作失败',
					icon: 'error'
				})
			}
		}
	}
}
</script>

<style lang="scss" scoped>
.container {
	min-height: 100vh;
	background-color: $background-gray;
	padding: $spacing-lg;
}

.form-group {
	margin-bottom: $spacing-xl;
}

.form-label {
	display: block;
	font-size: $font-size-body;
	font-weight: $font-weight-semibold;
	color: $text-dark-gray;
	margin-bottom: $spacing-sm;
}

.form-input {
	@extend .input;
	width: 100%;
}

.form-textarea {
	width: 100%;
	min-height: 88px;
	background-color: $card-white;
	border: 1px solid $border-gray;
	border-radius: $border-radius-md;
	padding: $spacing-md $spacing-lg;
	font-size: $font-size-body;
	color: $text-dark-gray;
	resize: none;
	
	&:focus {
		border-color: $primary-blue;
		box-shadow: 0 0 0 2px $primary-light-blue;
	}
}

.form-picker {
	width: 100%;
}

.picker-display {
	@extend .input;
	display: flex;
	justify-content: space-between;
	align-items: center;
	cursor: pointer;
}

.time-row {
	display: flex;
	gap: $spacing-md;
}

.time-item {
	flex: 1;
}

.time-label {
	display: block;
	font-size: $font-size-caption;
	color: $text-light-gray;
	margin-bottom: $spacing-xs;
}

.time-picker {
	width: 100%;
}

.priority-buttons {
	display: flex;
	gap: $spacing-sm;
	flex-wrap: wrap;
}

.priority-btn {
	@extend .btn-secondary;
	
	&.priority-urgent {
		&.active {
			background-color: $urgent-red;
			color: $card-white;
		}
	}
	
	&.priority-high {
		&.active {
			background-color: $high-orange;
			color: $card-white;
		}
	}
	
	&.priority-medium {
		&.active {
			background-color: $medium-purple;
			color: $card-white;
		}
	}
	
	&.priority-low {
		&.active {
			background-color: $low-gray;
			color: $card-white;
		}
	}
}

.tags-section {
	background-color: $card-white;
	border-radius: $border-radius-md;
	padding: $spacing-lg;
}

.available-tags {
	display: flex;
	flex-wrap: wrap;
	gap: $spacing-sm;
	margin-bottom: $spacing-md;
}

.tag-btn {
	@extend .btn-secondary;
	
	&.active {
		background-color: $primary-blue;
		color: $card-white;
	}
}

.custom-tag-input {
	display: flex;
	gap: $spacing-sm;
	align-items: center;
}

.tag-input {
	flex: 1;
	height: 36px;
	border: 1px solid $border-gray;
	border-radius: $border-radius-md;
	padding: 0 $spacing-md;
	font-size: $font-size-body;
	
	&:focus {
		border-color: $primary-blue;
	}
}

.add-tag-btn {
	height: 36px;
	padding: 0 $spacing-lg;
	background-color: $primary-blue;
	color: $card-white;
	border: none;
	border-radius: $border-radius-md;
	font-size: $font-size-body;
	
	&:disabled {
		background-color: $border-gray;
		color: $text-light-gray;
	}
}

.reminder-section {
	background-color: $card-white;
	border-radius: $border-radius-md;
	padding: $spacing-lg;
}

.reminder-toggle {
	display: flex;
	align-items: center;
	gap: $spacing-md;
	margin-bottom: $spacing-md;
}

.reminder-label {
	font-size: $font-size-body;
	color: $text-dark-gray;
}

.reminder-picker {
	width: 100%;
}

.type-buttons {
	display: flex;
	gap: $spacing-md;
	margin-bottom: $spacing-sm;
}

.type-btn {
	flex: 1;
	height: 48px;
	background-color: $card-white;
	border: 2px solid $border-gray;
	border-radius: $border-radius-md;
	display: flex;
	align-items: center;
	justify-content: center;
	gap: $spacing-xs;
	font-size: $font-size-body;
	color: $text-dark-gray;
	transition: all 0.2s ease;
	
	&.active {
		border-color: $primary-blue;
		background-color: $primary-light-blue;
		color: $primary-blue;
	}
	
	&:active {
		transform: scale(0.98);
	}
}

.type-desc {
	font-size: $font-size-caption;
	color: $text-light-gray;
	text-align: center;
}

.form-actions {
	margin-top: $spacing-2xl;
	padding-bottom: $spacing-xl;
}

.submit-btn {
	width: 100%;
	
	&:disabled {
		background-color: $border-gray;
		color: $text-light-gray;
		box-shadow: none;
	}
}
</style> 